package com.tencent.hummingbird.portal.controller;


import com.tencent.hummingbird.portal.exception.ServiceException;
import com.tencent.hummingbird.portal.pojo.Answer;
import com.tencent.hummingbird.portal.r.R;
import com.tencent.hummingbird.portal.service.IAnswerService;
import com.tencent.hummingbird.portal.vo.AnswerVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yxb
 * @since 2024-01-10
 */
@Slf4j
@RestController
@RequestMapping("/portal/answer")
public class AnswerController {
    @Autowired
    private IAnswerService answerService;
    @PostMapping("/postAnswer")
    public  R<Answer> answer(@AuthenticationPrincipal UserDetails userDetails, @RequestBody @Validated AnswerVO answerVO, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw ServiceException.unprocesabelEntity(bindingResult.getFieldError().getDefaultMessage());
        }
        Answer answer = answerService.saveAnswer(userDetails.getUsername(),answerVO);
        log.info("answer:{}",answer);
        return R.created(answer);

    }
    @GetMapping("/question/{questionId}")
    public R<List<Answer>> questionAnswers(@PathVariable Integer questionId){
        if(questionId==null){
            return R.notFound("id不存在");
        }
        List<Answer> answers =  answerService.getAnswersByQuestionId(questionId);
        return R.ok(answers);
    }
    @GetMapping("/solved/{answerId}/{questionId}")
    public R solved(@PathVariable Integer answerId,@PathVariable Integer questionId){
        answerService.accept(answerId,questionId);
        return R.ok("采纳成功");
    }
}
